package com.ics.cmsadmin.modules.pub.service;

import com.github.pagehelper.Page;
import com.ics.cmsadmin.frame.core.enums.LevelEnum;
import com.ics.cmsadmin.modules.basic.dao.CollectionDao;
import com.ics.cmsadmin.modules.basic.dao.LikeDao;
import com.ics.cmsadmin.modules.pub.bean.Course;
import com.ics.cmsadmin.modules.pub.bean.Unit;
import com.ics.cmsadmin.modules.pub.bean.UnitVO;
import com.ics.cmsadmin.modules.pub.dao.TeacherMapper;
import com.ics.cmsadmin.modules.pub.dao.TopicMapper;
import com.ics.cmsadmin.modules.pub.dao.UnitMapper;
import com.ics.cmsadmin.modules.pub.service.impl.CourseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("UnitService")
public class UnitService extends ResourceService<UnitMapper, Unit, Integer> {

    @Autowired
    private CourseServiceImpl courseServiceImpl;

    @Autowired
    private CollectionDao collectionDao;

    @Autowired
    private LikeDao likeDao;

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private TopicMapper topicMapper;

    public UnitVO get(Integer id, String userId) {
        Unit unit = super.get(id);
        if (unit == null) return null;
        return appendAttributes(unit, userId);
    }

    public List<UnitVO> getMultiple(Map<String, Object> param, String userId) {
        List<Unit> unitList = super.getMultiple(param);
        Page<UnitVO> page = new Page<>();
        page.addAll(unitList.stream().map(unit -> appendAttributes(unit, userId)).collect(Collectors.toList()));
        if (unitList instanceof Page) {
            page.setTotal(((Page) unitList).getTotal());
        } else {
            page.setTotal(unitList.size());
        }
        return page;
    }


    private UnitVO appendAttributes(Unit unit, String userId) {
        UnitVO unitVO = new UnitVO();
        BeanUtils.copyProperties(unit, unitVO);
        unitVO.setId(unit.getId());
        Map<String, Object> param = new HashMap<>();
        param.put("unitId", unit.getId());
        unitVO.setTopicCount(topicMapper.queryTotal(param));
        unitVO.setCollected(collectionDao.select(userId, LevelEnum.unit, String.valueOf(unit.getId())));
        unitVO.setLiked(likeDao.select(userId, LevelEnum.unit, unit.getId()));
        unitVO.setCollectCount(collectionDao.queryTotal(LevelEnum.unit, String.valueOf(unit.getId())));
        unitVO.setThumbUpCount(likeDao.queryTotal(LevelEnum.unit, String.valueOf(unit.getId())));
        unitVO.setTeacher(teacherMapper.select(unit.getTeacherId()));
        Course course = courseServiceImpl.get(unit.getCourseId(), userId);
        if (course != null) {
            unitVO.setHasBought(course.getHasBought());
            unitVO.setLearnerCount(course.getLearnerCount());
        }
        return unitVO;
    }
}
